<?php
@session_start();
require_once dirname(__FILE__).'./config/config.ini.php';
require_once dirname(__FILE__).'./config/config.vdb.php';
//require_once dirname(__FILE__).'./medoo.min.php';
require_once dirname(__FILE__).'./medoo.php';
require_once dirname(__FILE__).'./oci.php';
//namespace hyang\Conero;
//
/************extends 类扩展***************/
require_once(dirname(__FILE__).'/SocketClass.php');
abstract class ConeroAbstract
{
	public $user;

	private $_info;						//方法运行信息
	private $_console;					//console.log  文件
	private $_log;						//log 目录名称
	private $_sysFile;					//sysfile 下子目录
	private $_system;					//system.log 文件
	
	//template 私有成员		$tpl,$pNav,$pHead,$pDance,$pAdd,$pJson,$pConsole,$pAttr
	private $tpl;							//页面模板
	private $title;							//页面标题
	private $head;						//头部附加部分
	private $pNav;						//页面导航栏
	private $pHead;						//页头
	private $pDance;					//页面舞台
	private $pAdd;						//页面附加
	private $pJson;						//页面Json数据
	private $pConsole;					//页面平台
	private $pAttr;						//页面属性
	public $js;								//js目录
	public $css;							//css目录
	public $img;							//image目录
	//模板信息
	private $app;							//节点名。系统有多个节点组成，节点下包好多个页面，
	private	$page;						//页面
	/********************* 数据库扩展 
		Medoo  http://medoo.in/
	***********************/
	public $db;
	public $oci;//私人自写数据库函数
	/********************* 数据库扩展 ***********************/
	protected $key = 'hyang';				//公匙加密

	/****************CoenroAbstract 类扩展*******************/
	public $tcp;						// TCP/IP 协议
	public function __construct()
	{
		$this->user = '没有登入用户';
		//目录配置
		$this->_console = dirname(__FILE__).'/../log/console.log';
		$this->_log = dirname(__FILE__).'/../log/';
		$this->_sysFile = dirname(__FILE__).'/../';
		$this->_system = 'system.log';
		$this->js = P.'js/app';
		$this->css = P.'css/app';
		$this->img = P.'image/';
		//$this->pdo();//直接设置数据库连接
		//$this->oci();//报错			SQLSTATE[42S02]: pdo_oci_handle_factory: ORA-12154: TNS:could not resolve the connect identifier specified
		//类扩展
		$this->tcp = new Conero_socket();//PHP socket
	}

	public function setUser($name)
	{
		$_SESSION['user'] = $name;
		$this -> user = $_SESSION['user'];
	}

	public function quit($url='')
	{
		$_SESSION['user'] = '';
		$this -> user = '';
		//session_destroy();
		if($url) header('Loaction:'.$url);
	}
	public function getUser(){return (isset($_SESSION['user'])? $_SESSION['user']: '');}

	/*	中文目录乱码：
	 *	2015/12/17 星期四
	 *	获取以目录下的文件信息	（一级目录）
	 *	$dir  目录名称，$boolean 是否显示更简洁的文件信息
	 *	return array;
	 *	//ajax页面 调用方法存在问题  2016/1/7 星期四
	 */
	public function printDir($dir,$boolean=true,$feekdir=null)
	{	
		if(is_dir($dir))
		{	$feekdir = array();
			$data = array();$tmpArr = array();
			if ($dw = opendir($dir))
			{	
				$n= 0;
				while(($fscan = readdir($dw)) !== false)
				{
					if($feekdir && !in_array(trim($fscan),array(".",".."))) $feekdir[] = $fscan;
					if(strlen($fscan)>2 && !$boolean)
					{
						$n++;
						$url = $dir.$fscan;
						$url2dir =str_replace('/','\\',$url);
						$tmpArr = explode('.',$fscan);
						$type = $tmpArr[(count($tmpArr)-1)];
						unset($tmpArr[(count($tmpArr)-1)]);
						$cname = (is_array($tmpArr)? implode('.',$tmpArr) : $tmpArr);
						$data[$n]['name'] = $fscan;
						$data[$n]['cname'] = array($type,$cname);
						$data[$n]['url'] = $url;
						if($boolean)
						{
							$data[$n]['type'] = (filetype($url2dir)? filetype($url2dir) : $type);//文件类型
							$data[$n]['size'] = filesize($url2dir);//取得文件的大小
							$data[$n]['ctime'] = filectime($url2dir);//取得文件的 inode 修改时间
							$data[$n]['mtime'] = filemtime($url2dir);//取得文件修改时间
							$data[$n]['inode'] = fileinode($url2dir);//返回文件的 inode 节点号
							$data[$n]['atime'] = fileatime($url2dir);//文件上次访问时间
							$data[$n]['group'] = filegroup($url2dir);//取得该文件所属组的
							$data[$n]['owner'] = fileowner($url2dir);//取得文件的所有者
							$data[$n]['perms'] = fileperms($url2dir);//取得文件的权限
						}
					}
				}
				if($feekdir) return array('dir'=>$feekdir,'file'=>$data);
				return $data;
			}
		}
		else $this->_info = '函数参数不是有效目录！';
		return dirname(__FILE__).$dir;
	}
	//2016/4/21 星期四		返回目录的原始信息
	function getDir($dir)
	{
		if(is_dir($dir)){	
			$data = array();
			if ($dw = opendir($dir)){
				while(($fscan = readdir($dw)) !== false)
				{if(!in_array($fscan,array('.','..')))array_push($data,$fscan);}
				return array('dir'=>$dir,'data'=>$data);
			}
			return '无法读取到'.$dir.'目录下文件';
		}
		return $dir.' 根本不是目录，当前文件所在的目录为 '.dirname(__FILE__);;
	}
	/*
	 *	文件写入（创建文件）
	 *	$imfo 输入变量/信息,$style 文件前缀,$log-目标文件（log-文件下：可创建）,$url sysFile文件下的任何文件目录,$mode 文件读入模式（应用于二进制）
	 *	rerun 写入成功的文件目录
	 *
	 */
	public function console($imfo,$style=null,$log=null,$url=null,$mode=null)
	{
		$fileDir = (($log)? ($this->_log).$log : ($this->_console));
		($url)? ($fileDir= ($this->_sysFile).$url) : '';
		$system = "\n***************************\r\n CONSOLE_print (".self::sysdate()."):-	\r\n";
		$mode = (($mode)? $mode : 'a');

		$contents = (($style)? $style : $system);
		$input = (is_array($imfo)? print_r($imfo,true):$imfo);
		$contents .= $input."\n";
		//$contents .= $input."\r\n";

		if($style == 'none' || $style == 'N') $contents = $input;//只写入$imfo 变量

		if($handle = fopen($fileDir,$mode))
		{
			fwrite($handle,$contents);
			fclose($handle);
			$this->_info = $fileDir;
			return $fileDir;
		}else{
			return $fileDir;//无法读取时返回路径
		}
		
	}
	public function contents($sysfile,$safe=null)
	{
		$url = ($this->_sysFile).$sysfile;
		if($safe){return (is_file($url)? file_get_contents($url) : '');}
		$str = file_get_contents($url);
		return $str;
	}
	//删除文件并且记录信息
	public function deleteFile($url)
	{
		if(!is_file(($this->_sysFile).$url))
		{
			$this->_info= $url.'：文件不存在';
			return false;
		}
		if(unlink(($this->_sysFile).$url))
		{
			$imfo = "------->删除文件：".$url."\r\n";
			self::console($imfo,'',$this->_system);
			return true;
		}
		return false;
	}
	//系统日期
	public function sysdate($fmt=null){ $fmt=(($fmt)? $fmt : 'Y-m-d H:i:s');return date($fmt,time());}
	//方法信息
	public function info(){	echo '<br>Conero[Said]:<br> '.(($this->_info)? ($this->_info): '(:-_-:)'); }
	
	//前段与后台交付（利用cookie中间件-？中文乱码）
	public function setJsVal($name,$value,$day=1)
	{
		if(setcookie($name,$value,time()+3600*24*$day) == false)  setcookie($name,$value,time()-3600);
		else return true;

	}
	public function getJsVal($name,$array=null)
	{
		if(isset($_COOKIE[$name]) && $_COOKIE[$name]) return $_COOKIE[$name];
		if($array)	return $_COOKIE;
	}
	//2016/1/5 星期二	创建app(见classlog.php历史版本)
	public function createApp($appName)
	{
		//app.php
		//$appName = $appName;
		$action = array();
		$br = "\n";
		$dir = './hyang/app/'.$appName;
		$view = './hyang/view/'.$appName;
		$css = './public/css/app/'.$appName;
		$js = './public/js/app/'.$appName;
		$pre = $dir.'/'.$appName;					//perfix,suffix 前后缀
		$headtip = "\r\n/* ".date("Y-m-d H:i:s")." */\n";
		$action['app']['url'] = $pre.'.php';
		$action['app']['str'] = '<?php'.$br.$headtip.'
@session_start();'.$br.'
require_once \'/../.././LoadClass.php\';'.$br.'
$Load = new LoadClass();'.$br.'
$sid = $Load::appReady("'.$appName.'");'.$br.'
if((isset($_POST[\'model\']) && $_POST[\'model\'] != \'\') || (isset($_GET[\'model\']) && $_GET[\'model\'] != \'\')){'.$br.'
	$modelTo = (isset($_POST[\'model\'])? $_POST[\'model\'] : $_GET[\'model\']);'.$br.'
	modelTo($modelTo);	'.$br.'
}else{'.$br.'
	'.$br.'
	$'.$appName.' = new '.$appName.'();'.$br.'
	$sid = (isset($_SESSION[\'sid\'])? $_SESSION[\'sid\'] : \'\');'.$br.'
	if(isset($_GET[\'sid\']) && $_GET[\'sid\'] != \'\')'.$br.'
		$sid = $_GET[\'sid\'];'.$br.'
	switch($sid)'.$br.'
	{'.$br.'
		default:'.$br.'
			$'.$appName.' -> index();'.$br.'
	}'.$br.'
	exit;'.$br.'
}'.$br.'
?>'.$br.'
		';

		$action['class']['url'] = $pre.'.class.php';
		$action['class']['str'] = '<?php'.$br.$headtip.'
class '.$appName.' extends ControllerAbstract'.$br.'
{'.$br.'
	public function index()'.$br.'
	{'.$br.'
		header(\'Content-Type:text/html; charset=utf-8\');'.$br.'
		htmlHead(\'欢迎进入新模块！\');'.$br.'
		import("'.$appName.'","index","js");'.$br.'
		import("'.$appName.'","index","css");'.$br.'
		echo \'</head><body>\';'.$br.'
		echo \'<p id="navi">'.$br.'
		<a href="\'.HOME.\'guest.php">首页</a> '.$br.'
		<a href="javascript:window.history.back(-1);">Back</a>'.$br.'	
		</p>\';'.$br.'
		echo \'<p>'.$appName.' App创建成功</p>\';'.$br.'
		echo \'<p><b>(^_^)</b></p>\'; '.$br.'
		import("'.$appName.'","index");'.$br.'
		echo \'</body></html>\';'.$br.'
	}'.$br.'
}'.$br.'
?>'.$br.'
		';
		
		$action['model']['url'] = $pre.'.model.php';
		$action['model']['str'] = '<?php'.$br.$headtip.'
class model extends ModelAbstract'.$br.'
{'.$br.'

}'.$br.'
?>'.$br.'
		';

		$action['view']['url'] = './hyang/view/'.$appName.'/index.html';
		$action['view']['str'] = '<div id="Page"><p>系统应该是智能化的！！！</p><p>你造吗？我是被系统<i>自动生成！</i></p><p>And I am so happy for you,strating trade,y\'know!</p><p>Hola,My Brximl</p><p>By the way,I\'m Joshua Young</p></div>
		<div id="infomation"></div>
		';
		$action['css']['url'] = './public/css/app/'.$appName.'/index.css';
		$action['css']['str'] = $headtip."\n".'#page{border:1px solid #ff0066;background:#99ff00;margin:0 15% 1% 20%;}'.$br.'
#infomation{margin:2% 10% 0 10%; border:2px outset #006600;}'.$br.'
		';
		$action['js']['url'] = './public/js/app/'.$appName.'/index.js';
		$action['js']['str'] = $headtip."\n".'$(document).ready(function(){'.$br.'
	$("#infomation").html(H.version());'.$br.'
	alert("Y\'a so handsome!!");'.$br.'
});'.$br.'
		';
		if(is_dir($dir))
		{
			echo '模块已经存在！';
			return;
		}
		mkdir($dir);
		mkdir($view);		//view
		mkdir($css);	//css
		mkdir($js);		//js
		foreach($action as $v)
		{
			$fp = fopen($v['url'],"w+");
			fwrite($fp,$v['str']);
			fclose($fp);
		}
	}
	
	/*				2016/2/26 星期五
	*				采用模板
	*/
	public function pageInit()
	{
		htmlHead($this->title);
		if(!empty($this->app) && !empty($this->page)){
			import($this->app,$this->page,"js");
			import($this->app,$this->page,"css");
		}
		$tpl = (empty($this->tpl)? "templateV1.tpl":($this->tpl));	//默认模板	templateV1.tpl
		$this->useTpl($tpl);
	}
	//	2016/2/26 星期五	页面注册	$option = array("app"=>"v1","page"=>"v2"));
	public function register($option)
	{
		if(!is_array($option))
			return;
		if(isset($option["app"])) $this->app = $option["app"];
		if(isset($option["page"])) $this->page = $option["page"];
	}
	public function pHead($title=null,$html=null)
	{
		$this->title = $title;
		$this->head = $html;
	}
	/*		2016/2/26 星期五
			$navParam = array();
	*/
	public function setNav($navParam = null)
	{
		if(!is_array($navParam))
			return;
		$this->pNav = $navParam;
	}
	/*
	2016/2/26 星期五	设置页面参数		
	$param = array("pNav"=>"xhtml1","pHead"=>"xhtml2","pDance"=>"xhtml3","pAdd"=>"xhtml4","pJson"=>"xhtml5","pConsole"=>"xhtml6");
	*/
	public function setpParam($param)
	{
		if(!is_array($param)) return;
		if(isset($param["pNav"])) $this->pNav = $param["pNav"];
		if(isset($param["pHead"])) $this->pHead = $param["pHead"];
		if(isset($param["pDance"])) $this->pDance = $param["pDance"];
		if(isset($param["pAdd"])) $this->pAdd = $param["pAdd"];
		if(isset($param["pJson"])) $this->pJson = $param["pJson"];
		if(isset($param["pConsole"])) $this->pConsole = $param["pConsole"];
	}
	//	2016/2/26 星期五	获取页面参数
	public function getpParam()
	{
		return array("pNav"=>$this->pNav,"pHead"=>$this->pHead,"pDance"=>$this->pDance,"pAdd"=>$this->pAdd,"pJson"=>$this->pJson,"pConsole"=>$this->pConsole);
	}
	//	2016/2/26 星期五	设置模板
	public function useTpl($tplName=null)
	{
		if(empty($tplName)) return;
		$file = SYSDIR.HYANG.'tpl/'.$tplName;
		if(is_file($file)){
			include_once($file);
			$this->tpl = $file;
		}
	}
	//	2016/2/26 星期五	设置页面属性
	public function setpAttr($pAttr)
	{
		$this->pAttr = $pAttr;
	}
	//	2016/2/26 星期五	获取属性
	public function getpAttr($name)
	{
		$pAttr = $this->pAttr;
		if(isset($pAttr[$name])) return $pAttr[$name];
		return $pAttr;
	}

	//		2016/3/9 星期三		PHP类中加载外部类：（可选）			引入 Action.index.php
	public function Action($className,$app,$debug=null)
	{
		$action = str_replace('/','\\',dirname(__FILE__).'/app/'.$app.'/Action.'.$className.'.php');
		if($debug){
			$callback = '<p>当前文件路径:“'.dirname(__FILE__).'”';
			$callback .= '<br>eval 函数执行语句：“ $obj = new '.$className.'();  ”';
			$callback .= '<br>action文件：'.$action;
			return $callback.'</p>';
		}
		if(is_file($action)){
			include_once($action);
			eval("\$obj = new ".$className."();");
			return $obj;
		}else{
			return '<p>“'.$action.'”文件引入失败！</p>';
		}
	}
	//文件名称解构
	function fileInfo($file)
	{
		$retVal = array();
		$tmp = explode('.',$file);
		$lastK = count($tmp)-1;
		$suffix = $tmp[$lastK];
		$perffix = str_replace($suffix,'',$file);
		if(substr_count($perffix,'/')>0){
			$tmp2 = explode('/',$perffix);
			$lastK2 = count($tmp2)-1;
			$retVal['perffix'] = rtrim($tmp2 [$lastK2],'.');
			array_pop($tmp2);
			$retVal['dir'] = implode('/',$tmp2);
		}else{
			$retVal['perffix'] = rtrim($perffix,'.');
		}
		$retVal['suffix'] = $suffix;
		return $retVal;
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~生成器
	/*		2016/3/9 星期三
	  *		$data = {"text":attr},attr={name:value} 或者 $data = array("text","text",...)
	  *
	  */
	public function eles($data,$ele,$link=false,$single=false)
	{
		$xhtml = '';
		if(is_array($data)){
			foreach($data as $k=>$v){
				$xhtml .= '<'.$ele;
				$attr = array();
				if(is_array($v)){
					foreach($v as $kk=>$vv){
						$attr[] = $kk.'="'.$vv.'"';
					}
					$xhtml .= implode(" ",$attr);
					$xhtml .= '>'.(($link)? '<a href="javascript:void(0)">'.$k.'</a>' : $k) .(($single)? '':'</'.$ele.'>');
				}else{
					$xhtml .= '>'.(($link)? '<a href="javascript:void(0)">'.$v.'</a>' : $v).(($single)? '':'</'.$ele.'>');
				}
			}
		}
		return $xhtml;
	}
	//	计算任意两天的差距	$d1-$d2	格式：Y-m-d		2016/3/16 星期三	: 不适用时间日期对象
	public function datediff($d1,$d2,$name=null)
	{
		$d1Arr = explode('-',$d1);
		$d2Arr = explode('-',$d2);
		$d = $d1Arr[2]-$d2Arr[2];
		if($d<0){
			$d += 30;
			$d1Arr[1] -= 1;
		}
		$m = $d1Arr[1]-$d2Arr[1];
		if($m<0){
			$m += 12;
			$d1Arr[0] -= 1;
		}
		$y = $d1Arr[0]-$d2Arr[0];
		if($y<0) $y =  0;
		$desc = (($y>0)? $y.'年':'').(($m>0)? $m.'月' : '').(($d>0)? '零'.$d.'天' : '');
		$back = array('y'=>$y,'m'=>$m,'d'=>$d,'h'=>($date["yday"]*24),'mi'=>($date["yday"]*24*60),'s'=>($date["yday"]*24*60*60),'desc'=>$desc);
		if(isset($back[$name])){
			return $back[$name];
		}
		return $back ;
		//echo $d1.'<br>'.$d2;
	}
//2016/4/1 星期五	  数据库扩展，应用medoo框架（类）
	public function pdo($debug=false)
	{
		$option =array(
			// required
			'database_type' => DB_TYPE,
			'database_name' => DB_NAME,
			'server' => DB_HOST,
			'username' => DB_USER,
			'password' => DB_PASSW,
			'charset' => DB_CHARSET,

			// [optional]
			'port' => DB_PORT,

			// [optional] Table prefix
			//'prefix' => 'PREFIX_',

			// driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
			'option' => array(
				PDO::ATTR_CASE => PDO::CASE_NATURAL
			)
		);
			if($debug){
				echo'<prev>';
				print_r($option);
				echo '<br>';
			}
		$this->db = new medoo($option);
		return $this->db;
	}
	//私人数据库处理，for oracle  oci
	public function oci()
	{
		$option = array(
				'user'=>DB_USER,
				'password'=>DB_PASSW,
				'host'=>DB_HOST,
				'port'=>DB_PORT,
				'dbname'=>DB_NAME
			);
		$this->oci = new oci($option);
		return $this->oci;
	}
	/*
		2016/5/5 星期四
		简单在封装excel文件读取操作
		参数： *$file文件名,*$cols最大行列,$type 类型
	*/
	public function excel($file,$cols,$getAll=null,$type=null)
	{
		$dir = SYSDIR.LIB.'PHPExcel/';
		$vdb = SYSDIR.VDB.$file;//$vdb = SYSDIR.VDB.'data/internet.xls';
		//if(!is_file($file)) return $vdb.' 文件无法打开，数据读取失败！';

		require_once $dir.'PHPExcel.php';
		require_once $dir.'PHPExcel/IOFactory.php';
		$type = $type? $type : 'Excel5';
		$objReader = PHPExcel_IOFactory::createReader($type);//Excel文件格式不相同报错
		$objPHPExcel = $objReader->load($vdb);
		$sheet = $objPHPExcel->getSheet(0); // 读取第一個工作表
		$highestRow = $sheet->getHighestRow(); // 取得总行数
		$highestColumm = $sheet->getHighestColumn(); // 取得总列数
		$item = $_POST['item'];
			//$customPropertyList = $objPHPExcel->getProperties()->getCustomProperties();
			//echo $sheet->getCell('A1')->getValue();
			$data = array();
			$column = $this->letter_array(strtoupper($cols));//$column = array("A","B","C","D","E","F","G","H","I","J","K","L");
			$key = 0;
			$i = $getAll? 2 : 1;
			for($i;$i<=$highestRow;$i++){
				foreach($column as $k=>$v){
					$keyValue = $sheet->getCell($v.$i)->getValue();
					$data[$key][$k] = (empty($keyValue)? "":$keyValue);
				}
				$data[$key]["dataRow"] = $i;//xls 实际行
				$key++;
			}
			return $data;
	}
	//指定一个字母生成一个重A-$ 的数组	2016/5/5 星期四
	public function letter_array($let)
	{
		$Arr = array();
		$le_ord = ord($let);//字符的ascII码		A-Z: 65-90,a-z: 97-122
		if($le_ord>= 65 && $le_ord <= 90){
			for($i=65; $i<=$le_ord; $i++) array_push($Arr,chr($i));
		}elseif($le_ord>= 97 && $le_ord <= 122){
			for($i=97; $i<=$le_ord; $i++) array_push($Arr,chr($i));
		}
		return $Arr;
	}
//个人方法<- _________________________________________________________________________________________->	网上应用
	/*
	 *	2015/12/18 星期五
	 *	二进制处理		：参考 http://bzyyc.happy.blog.163.com/blog/static/6143064720117254592445/
	 *
	 *
	 *
	 */
	private function _asc2bin($str)
	{
		$data = '';
		$len = strlen($str); 
		for ($i=0; $i<$len; $i++) $data.=sprintf("%02x",ord(substr($str,$i,1))); 
 		return $data; 
	}
	public function asc2bin($str,$format='H*')
	{
		return pack($format,self::_asc2bin($str));
	}

	//2015/12/18 星期五
	//http://my.oschina.net/alexskywinner/blog/136677	参考
	public function str2bin($str){
		//1.列出每个字符
		$arr = preg_split('/(?<!^)(?!$)/u', $str);
		//2.unpack字符
		foreach($arr as &$v){
			$temp = unpack('H*', $v);
			$v = base_convert($temp[1], 16, 2);
			unset($temp);
		}
		return join(' ',$arr);
	}
	public function bin2str($str){
		$arr = explode(' ', $str);
		foreach($arr as &$v){
			$v = pack("H".strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));
		}
		return join('', $arr);
	}

	//实用的PHP带公钥加密类分享 -http://www.jb51.net/article/54048.htm(类合并，2015/12/25 星期五)
	//	测试无效

	private function _keyed($txt,$encrypt_key)
	{
		$encrypt_key = md5($encrypt_key);
		$ctr=0;
		$tmp = '';
		for ($i=0;$i<strlen($txt);$i++){
		  if ($ctr==strlen($encrypt_key)){
			$ctr=0;
		  }
		  $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
		  $ctr++;
		}
		return $tmp;
  }
  //加密
  public function encrypt($txt,$key=''){
    if(empty($key)){
      $key=$this->key;
    }
    srand((double)microtime()*1000000);
    $encrypt_key = md5(rand(0,32000));
    $ctr=0;
    $tmp = '';
    for ($i=0;$i<strlen($txt);$i++) {
      if ($ctr==strlen($encrypt_key)){
        $ctr=0;
      }
      $tmp.= substr($encrypt_key,$ctr,1).(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
      $ctr++;
    }
    return $this->_keyed($tmp,$key);
  }
 //解密
  public function decrypt($txt,$key=''){
	if(empty($key)){
	  $key=$this->key;
	}

	$txt = $this->_keyed($txt,$key);
	$tmp = '';
	for ($i=0;$i<strlen($txt);$i++){
	  $md5 = substr($txt,$i,1);
	  $i++;
	  $tmp.= (substr($txt,$i,1) ^ $md5);
	}
	return $tmp;
  }
  //设置公匙
  public function setKey($key){
    if(empty($key)){
      return null;
    }
    $this->key=$key;
  }
  //获取公匙
  public function getKey(){return $this->key;}

}
?>